#!/usr/bin/env ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

require 'set'
require 'open3'
require_relative '../defconfig.rb'

names = Set.new %w[
  REDIS_HOST
  REDIS_PORT
  ES_HOST
  ES_PORT
  ES_USER
  ES_PASSWORD
  SEND_MAIL_HOST
  SEND_MAIL_PORT
  SRV_HTTP_RESULT_HOST
  SRV_HTTP_RESULT_PORT
  lab
]

defaults = relevant_defaults(names)

service_authentication = relevant_service_authentication(names)
defaults.merge!(service_authentication)

env = docker_env(defaults)

DEFAULT_LKP = '/c/lkp-tests'
DEFAULT_CCI = '/c/compass-ci'
SRV_HTTP_RESULT_HOST = defaults['SRV_HTTP_RESULT_HOST'] || Open3.capture3('curl ip.sb')[0].chomp
SRV_HTTP_RESULT_PORT = defaults['SRV_HTTP_RESULT_PORT'] || '20007'
docker_rm 'extract-stats'

cmd = %w[
  docker run
  --name extract-stats
  --restart=always
  -d
] + env + %W[
  -e LKP_SRC=#{DEFAULT_LKP}
  -e CCI_SRC=#{DEFAULT_CCI}
  -e SRV_HTTP_RESULT_HOST=#{SRV_HTTP_RESULT_HOST}
  -e SRV_HTTP_RESULT_PORT=#{SRV_HTTP_RESULT_PORT}
  -v #{ENV['LKP_SRC']}:#{DEFAULT_LKP}
  -v /etc/localtime:/etc/localtime:ro
  -v #{ENV['CCI_SRC']}:#{DEFAULT_CCI}
  -v /srv/result:/result
  --log-opt mode=non-blocking
  --log-opt max-buffer-size=4m
  extract-stats
]

cmd += ['sh', '-c', 'umask 002 && ./extract-stats']

system(*cmd)
